//
//  YDFMDB.m
//  YDTestDrive
//
//  Created by ios on 2017/3/13.
//  Copyright © 2017年 ios. All rights reserved.
//

#import "YDFMDB.h"

#import "FMDB.h"

#define SQLITE_NAME @"YDData.sqlite"
static YDFMDB *ydFmdb;

@interface YDFMDB ()

@property (nonatomic, strong) FMDatabaseQueue *queue;

@end
@implementation YDFMDB

+ (instancetype)instence
{
    if (ydFmdb == nil) {
        ydFmdb = [[YDFMDB alloc] init];
    }
    return ydFmdb;
    
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (ydFmdb == nil) {
        ydFmdb = [super allocWithZone:zone];
    }
    return ydFmdb;
}

- (id)mutableCopy
{
    return self;
}

- (instancetype)init
{
    if (self = [super init]) {
        
        //获取沙盒中的文件名
        NSString *fileName = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:SQLITE_NAME];
        
        self.queue = [FMDatabaseQueue databaseQueueWithPath:fileName];
    }
    return self;
}

- (BOOL)isExistWithTableName:(NSString *)tableName
{
    if (tableName == nil) {
        NSLog(@"表名不能为空");
        return NO;
    }
    
    __block BOOL result;
    [self.queue inDatabase:^(FMDatabase *db) {
        result = [db tableExists:tableName];
    }];
    return result;
}

- (BOOL)createTableWithName:(NSString *)name keys:(NSArray *)keys
{
    if (name == nil) {
        NSLog(@"表名不能为空");
        return NO;
    } else if (keys == nil) {
        NSLog(@"字段名不能为空");
        return NO;
    }
    
    __block BOOL result;
    
    [self.queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"CREATE TABLE IF NOT EXIST %@(ID INTEGER PRIMARY AUTOINCREMENT NOT NULL "];
    }];

    return result;
}


@end
